import getpass

import win32security

import ntsecuritycon as con

def add_sec_by_file(file):
    sd = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    ace_count = dacl.GetAceCount()
    for i in range(0, ace_count):
        rev, access, usersid = dacl.GetAce(i)
        user, group, type = win32security.LookupAccountSid('', usersid)
        if type == 1:
            add_sec_by_name(file, user)


def remove_sec_by_file(file):
    sd = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    ace_count = dacl.GetAceCount()
    for i in range(0, ace_count):
        rev, access, usersid = dacl.GetAce(i)
        user, group, type = win32security.LookupAccountSid('', usersid)
        if type == 1:
            remove_sec_by_name(file, user)


def add_sec_by_name(file, user_name):
    user_now, domain, type = win32security.LookupAccountName(None, user_name)
    sd = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    access = con.FILE_GENERIC_WRITE | con.FILE_GENERIC_READ | con.FILE_GENERIC_EXECUTE | con.FILE_ALL_ACCESS
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, access, user_now)

    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION, sd)

def remove_sec_by_name(file, user_name):
    user_now, domain, type = win32security.LookupAccountName(None, user_name)
    sd = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    access = con.FILE_GENERIC_WRITE | con.FILE_GENERIC_READ | con.FILE_GENERIC_EXECUTE | con.FILE_ALL_ACCESS
    dacl.AddAccessDeniedAce(win32security.ACL_REVISION, access, user_now)

    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION, sd)


def print_all_user(file):
    sd = win32security.GetFileSecurity(file, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    ace_count = dacl.GetAceCount()
    for i in range(0, ace_count):
        rev, access, usersid = dacl.GetAce(i)
        user, group, type = win32security.LookupAccountSid('', usersid)
        print('User: {}/{}'.format(group, user), rev, access)


if __name__ == '__main__':
    FILENAME = "c:\\logs\\screen.exe"
    remove_sec_by_file(FILENAME)
